<template>
  <el-row>
    <el-col :span="8">
      <div class="btn-container">
        <el-button type="primary" @click="saveClick">保存</el-button>
      </div>
      <el-tree
        ref="menuRef"
        class="tree-border"
        :data="menuTree"
        show-checkbox
        node-key="menuId"
        :check-strictly="false"
        :expand-on-click-node="false"
        :check-on-click-node="false"
        :check-on-click-leaf="false"
        empty-text="加载中，请稍候"
        :props="{ label: 'menuName', children: 'children' }"
        @node-click="handleNodeClick"
      ></el-tree>
    </el-col>
    <el-col :span="16">
      <PermissionTable
        ref="permissionTableRef"
        :menuId="selectedMenu?.menuId"
        :menuName="selectedMenu?.menuName"
        :roleId="props.roleId"
      ></PermissionTable>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { nextTick, ref, useTemplateRef, watch } from 'vue'
import { menuApi, roleApi } from '@/api'
import { RoleMenuTree, SaveRoleMenuDto, SysRoleMenu } from '@/api/system/roleTyppe'
import { MenuTypeEnum } from '@/enums/dictEnum'
import { ElMessage, TreeInstance } from 'element-plus'
import PermissionTable from './PermissionTable.vue'

// Props定义
interface Props {
  systemId: string
  roleId: string
}
const props = withDefaults(defineProps<Props>(), {
  systemId: '',
  roleId: ''
})

// 菜单树实例
const menuRef = useTemplateRef<TreeInstance>('menuRef')

// 菜单树数据
const menuTree = ref<RoleMenuTree[]>([])

// 选中的菜单
const selectedMenu = ref<RoleMenuTree>()

// 角色菜单列表
const roleMenuList = ref<SysRoleMenu[]>([])

/**
 * 查询菜单树
 */
const findMenuTree = async () => {
  if (!props.systemId) {
    return
  }
  const params = {
    systemId: props.systemId,
    menuType: MenuTypeEnum.MENU
  }
  menuApi
    .findMenuTree(params)
    .then((res: any) => {
      menuTree.value = res || []
      setTreeNodes(menuTree.value)
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询菜单树失败')
    })
}

// 处理节点点击事件
const handleNodeClick = (data: any) => {
  selectedMenu.value = data
  console.log('点击节点:', selectedMenu.value)
}

// 查询角色菜单列表
const findRoleMenuList = async () => {
  if (!props.roleId) {
    return
  }
  roleApi
    .findRoleMenuList(props.roleId)
    .then((res: any) => {
      roleMenuList.value = res || []
      setTreeChcked()
      selectedMenu.value = { menuId: '', menuName: '' }
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询角色菜单列表失败')
    })
}

// 设置树节点禁用状态
const setTreeNodes = (treeData: RoleMenuTree[]) => {
  if (!treeData || !treeData.length) return
  const isDisabled = !props.roleId
  treeData.forEach((node) => {
    node.disabled = isDisabled
    if (node.children && node.children.length) {
      setTreeNodes(node.children)
    }
  })
}

// 设置树节点选中状态
const setTreeChcked = () => {
  menuRef.value!.setCheckedKeys([], false)
  if (!roleMenuList.value.length) {
    return
  }
  roleMenuList.value.forEach((v) => {
    nextTick(() => {
      menuRef.value?.setChecked(v.menuId, true, false)
    })
  })
}

// 保存点击事件
const saveClick = () => {
  const checkedKeys = menuRef.value!.getCheckedKeys() as string[]
  const halfCheckedKeys = menuRef.value!.getHalfCheckedKeys() as string[]
  if (!checkedKeys.length && !halfCheckedKeys.length) {
    ElMessage.warning('请先选择菜单')
    return
  }
  const params: SaveRoleMenuDto = {
    roleId: props.roleId,
    menuIds: checkedKeys.concat(halfCheckedKeys)
  }

  roleApi
    .saveRoleMenu(params)
    .then(() => {
      ElMessage.success('保存成功')
    })
    .catch((err: any) => {
      ElMessage.error(err || '保存失败')
    })
}

watch(
  () => props.systemId,
  (newVal) => {
    findMenuTree()
  },
  { immediate: true }
)
watch(
  () => props.roleId,
  (newVal) => {
    setTreeNodes(menuTree.value)
    findRoleMenuList()
  }
)
</script>

<style scoped lang="less">
.btn-container {
  margin-bottom: 10px;
}
</style>
